package com.oracle.config.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.oracle.config.service.api.SystemChartApi;
import com.oracle.mapper.LogsMapper;
import com.oracle.mapper.NewsMapper;
import com.oracle.vo.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class SystemChartServiceImpl implements SystemChartApi {

    @Autowired
    private LogsMapper logsMapper;
    @Autowired
    private NewsMapper newsMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${cache_key_prefix}")
    private String cachePrefix;

    @Override
    public ResultEntity<List<Map<String, Object>>> getExecuteTypeAndCount() {
        List<Map<String, Object>> mapList = null;
        //定义redis缓存的key
        String cacheKey = this.cachePrefix+"logs";
        //获取缓存的JSON数据
        String redisCache = (String)this.redisTemplate.opsForValue().get(cacheKey);
        if (redisCache==null || "".equals(redisCache)){
            System.out.println("redis没有数据");
            //没有数据进行查询数据库
            mapList = this.logsMapper.selectExecuteTypeAndCount();
            //转为json
            String jsonString = JSONObject.toJSONString(mapList);
            //存储redis，定义过期时间
            this.redisTemplate.opsForValue().set(cacheKey,jsonString,24,TimeUnit.HOURS);
        }else {
            System.out.println("redis存在数据");
            mapList = (List<Map<String,Object>>) JSONArray.parse(redisCache);
        }

        return new ResultEntity<List<Map<String, Object>>>(ResultEntity.CODE_SUCCESS,ResultEntity.MSG_SUCCESS,mapList);
    }

    @Override
    public ResultEntity<List<Map<String, Object>>> getNewsCategoryAndCount() {
        List<Map<String, Object>> mapList = null;
        //定义redis缓存的key
        String cacheKey = this.cachePrefix+"news";
        //获取缓存的JSON数据
        String redisCache = (String)this.redisTemplate.opsForValue().get(cacheKey);
        if (redisCache==null || "".equals(redisCache)){
            System.out.println("redis没有数据");
            //没有数据进行查询数据库
            mapList = this.newsMapper.selectNewsCategoryAndCount();
            //转为json
            String jsonString = JSONObject.toJSONString(mapList);
            //存储redis，定义过期时间
            this.redisTemplate.opsForValue().set(cacheKey,jsonString,24,TimeUnit.HOURS);
        }else {
            System.out.println("redis存在数据");
            mapList = (List<Map<String,Object>>) JSONArray.parse(redisCache);
        }
        return new ResultEntity<List<Map<String, Object>>>(ResultEntity.CODE_SUCCESS,ResultEntity.MSG_SUCCESS,mapList);
    }
}
